package com.caissa.springboot.starter.kafka.consumer.retry;

import com.base.springboot.starter.kafka.consumer.exception.CaissaConsumerDirectStoreErrorMsgException;
import com.base.springboot.starter.kafka.consumer.exception.CaissaConsumerRetryThenStoreErrorMsgException;
import org.springframework.retry.backoff.ExponentialBackOffPolicy;
import org.springframework.retry.policy.SimpleRetryPolicy;
import org.springframework.retry.support.RetryTemplate;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeoutException;

/**
 * Description:
 * User: wangwei
 * Date: 2021-06-18 9:48 上午
 */
public class DefaultBackOffRetryTemplate extends RetryTemplate {

    public DefaultBackOffRetryTemplate() {
        this(3, 2, 30 * 1000);
    }

    public DefaultBackOffRetryTemplate(int maxAttempts, double multiplier, long maxInterval) {
        super();
        Map<Class<? extends Throwable>, Boolean> exceptionMap = new HashMap<>();

        // 定义需要重试的异常
        exceptionMap.put(IllegalArgumentException.class, false);
        exceptionMap.put(CaissaConsumerDirectStoreErrorMsgException.class, false);
        exceptionMap.put(TimeoutException.class, true);
        exceptionMap.put(CaissaConsumerRetryThenStoreErrorMsgException.class, true);

        SimpleRetryPolicy simpleRetryPolicy = new SimpleRetryPolicy(3, exceptionMap, true);

        this.setRetryPolicy(simpleRetryPolicy);

        ExponentialBackOffPolicy exponentialBackOffPolicy = new ExponentialBackOffPolicy();
        exponentialBackOffPolicy.setInitialInterval(2000);
        exponentialBackOffPolicy.setMultiplier(multiplier);
        exponentialBackOffPolicy.setMaxInterval(maxInterval);

        this.setBackOffPolicy(exponentialBackOffPolicy);
    }
}
